/* Copyright 2001,2002,2003 NAH6 BV
 * All Rights Reserved
 *
 *  $Header: /var/lib/cvs/secphone/ui/audio/AudioDevice.cpp,v 1.4 2003/11/21 12:39:24 itsme Exp $
 *
 * Implementation of class AudioDevice.
 *
 * This module handles setting and getting of the general device volume
 *
 * currently this is only used by the VolumeManager
 * ( via SpipcHandler::{Request|Set}Volume )
 *
 * Used as global variable defined in SpipcHandler.cpp
 *
 *
 */
#include <windows.h>

#include "debug.h"

#include "AudioDevice.h"
#include <mmsystem.h>

AudioDevice::AudioDevice()
{
    m_hwo= NULL;
    m_deviceid_valid= Open() && GetID(m_deviceid);
    Close();
}

AudioDevice::~AudioDevice()
{
    if (m_hwo)
        Close();
}

bool AudioDevice::Open()
{
    WAVEFORMATEX wfe;

    wfe.nSamplesPerSec= 11025;
    wfe.wFormatTag= WAVE_FORMAT_PCM;
    wfe.nChannels= 1;
    wfe.wBitsPerSample= 16;
    wfe.nBlockAlign= 2;
    wfe.nAvgBytesPerSec= wfe.nSamplesPerSec*wfe.nBlockAlign;

    wfe.cbSize= 0;

    MMRESULT res= waveOutOpen( &m_hwo, WAVE_MAPPER, &wfe, NULL, NULL, CALLBACK_NULL);
    if( res!=MMSYSERR_NOERROR )
    {
        m_hwo= NULL;
        debug("ERROR waveOutOpen: %08lx\n", res);
        return false;
    }
    return true;
}
bool AudioDevice::GetID(UINT& devid)
{
    if (m_hwo==NULL)
        return false;
    MMRESULT res= waveOutGetID(m_hwo, &devid);
    if (res!=MMSYSERR_NOERROR )
    {
        debug("ERROR waveOutGetID: %08lx\n", res);
        return false;
    }

    return true;
}
bool AudioDevice::Close()
{
    if (m_hwo==NULL)
        return false;
    MMRESULT res= waveOutClose( m_hwo ); 
    if (res!=MMSYSERR_NOERROR)
    {
        debug("ERROR: waveOutClose: %08lx\n", res);
        return false;
    }
    m_hwo= NULL;

    return true;
}
bool AudioDevice::GetVolume(DWORD& volume)
{
    if (!m_deviceid_valid && m_hwo==NULL)
        return false;
    DWORD dwVolume;
    MMRESULT res= waveOutGetVolume(m_hwo==NULL?(HWAVEOUT)m_deviceid : m_hwo, &dwVolume);
    if( res!=MMSYSERR_NOERROR )
    {
        debug("ERROR waveOutSetVolume: %08lx\n", res);
        return false;
    }

    volume= dwVolume&0xffff;

    return true;
}

bool AudioDevice::SetVolume(DWORD volume)
{
    if (!m_deviceid_valid && m_hwo==NULL)
        return false;
    MMRESULT res= waveOutSetVolume(m_hwo==NULL?(HWAVEOUT)m_deviceid : m_hwo, volume);
    if( res!=MMSYSERR_NOERROR )
    {
        debug("ERROR waveOutSetVolume: %08lx\n", res);
        return false;
    }
    return true;
}

